﻿using System;
using System.Collections.ObjectModel;
using System.Linq;

namespace TinyContainer
{
    /// <summary>
    /// Represents a collection of mapped object instances.
    /// </summary>
    public class MappingCollection : Collection<Mapping>
    {

        /// <summary>
        /// Inserts an object type at the specified index.
        /// </summary>
        /// <returns>
        /// The object instance that corresponds to the specified <c>Object.Type</c> and <c>Object.Name</c>.
        /// </returns>        
        /// <param name="type">The <c>Object.Type</c> of the object.</param>        
        /// <param name="name">The <c>Object.Name</c> of the object.</param>
        public Mapping this[Type type, string name]
        {
            get
            {
                var map = (from m in this where m.Interface == type && m.Name == name select m).FirstOrDefault();
                if (map != null)
                    return map;
                else
                {
                    map = new Mapping()
                    {
                        Interface = type,
                        Name = name
                    };
                    this.Add(map);
                    return map;
                }
            }
        }


        /// <summary>
        /// Deletes the object instance.
        /// </summary>
        /// <param name="instance">The name of the object instance.</param>
        public void RemoveInstance(object instance)
        {
            var map = (from m in this where m.Instance.Equals(instance) select m).FirstOrDefault();
            if (map != null)
            {
                map.Instance = null;
            }
        }

        /// <summary>
        /// Determines whether the specified object type is registered.
        /// </summary>
        /// <param name="type">The <c>Object.Type</c> of the object instance.</param>
        /// <param name="name">The <c>Object.Name</c> of the object instance.</param>
        /// <returns>
        ///   <c>true</c> if the specified type is registered; otherwise, <c>false</c>.
        /// </returns>
        public bool IsRegistered(Type @type, string name)
        {
            var map = (from m in this where m.Interface == type && m.Name == name select m).FirstOrDefault();
            return map != null && (map.Class != null || map.Instance != null);
        }
    }
}
